﻿var WindJS = WindJS || {};
WindJS._global = WindJS._global || {};

//require Priority
WindJS.wire = function (object, event, method)
{
	if (object[event] == undefined || false == object[event].hasOwnProperty("_handlers"))
	{
		//save object[event] to f
		var f = object[event] instanceof Function ? object[event].bind(object) : undefined;

		//redefine object[event] with a function used to raise the event
		object[event] = function (a, b, c, d, e, f)
		{
			var ret = undefined;
			object[event]._handlers.forEach(function (element)
			{
				ret = element(a, b, c, d, e, f);
			});
			return ret;
		}

		object[event]._handlers = [];

		//if the object[event] is callable then add it to the event handler list
		if (f !== undefined) object[event]._handlers.push(f);
	}
	object[event]._handlers.push(method);
}

WindJS.unwire = function (object, event, method)
{
	var i = object[event]._handlers.indexOf(method);
	object[event]._handlers[i] = function () { };
}

WindJS.uniwire = function (object, event, method)
{
	object[event] = method;
}

WindJS.ununiwire = function (object, event, method)
{
	object[event] = function () { };
}

WindJS.subscribe = function (event, method)
{
	WindJS.wire(WindJS._global, event, method);

}

WindJS.publish = function (topicid, e)
{
	if (false == WindJS._global[topicid] instanceof Function) return;
	//raise event
	WindJS._global[topicid](e);
}

WindJS.unsubscribe = function (topicid, method)
{
	WindJS.unwire(WindJS._global, topicid, method);
}

WindJS.wireEx = function (object, event, method, convertMethod)
{
	function convert(e)
	{
		convertMethod(e);
		method(e);
	}

	WindJS.wireEx(object, event, convert);
}

WindJS.subscribeEx = function (topic, method, convertMethod)
{
	function convert(e)
	{
		convertMethod(e);
		method(e);
	}

	WindJS.subscribe(topic, convert);
}